package com.shoujifeng.snowmusic.player;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import com.shoujifeng.snowmusic.player.R;
import com.shoujifeng.snowmusic.entity.Mp3Info;
import com.shoujifeng.snowmusic.player.utils.MusicPlayer;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MusicActivity extends Activity {
    /** Called when the activity is first created. */
	public ListView listView;
	private ListAdapter mAdapter;
	private List<Mp3Info> mp3Infos;
	private MusicPlayer musicPlayer;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
    }
    public void init() {
    	musicPlayer  = new MusicPlayer(MusicActivity.this);
		listView = (ListView) findViewById(R.id.all_music_list);
		mp3Infos = musicPlayer.getMp3Infos(MusicActivity.this);
		MusicPlayer.musicInfos =new ArrayList<Mp3Info>();
		MusicPlayer.musicInfos = mp3Infos;
		setListAdpter(mp3Infos);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				if (mp3Infos != null) {
					Intent intent = new Intent(MusicActivity.this,
							MusicPlayActivity.class);
					 Mp3Info mp3Info = mp3Infos.get(position);
					 String url = mp3Info.getUrl();
			            intent.putExtra("url", url);         
			         MusicPlayer.position = position;   
					startActivity(intent);
				}
			}
		});
	}

	public void setListAdpter(List<Mp3Info> mp3Infos) {
		List<HashMap<String, String>> mp3list = new ArrayList<HashMap<String, String>>();
		for (Iterator iterator = mp3Infos.iterator(); iterator.hasNext();) {
			Mp3Info mp3Info = (Mp3Info) iterator.next();
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("title", mp3Info.getTitle());
			map.put("Artist", mp3Info.getArtist());
			map.put("duration", String.valueOf(mp3Info.getDuration()));
			map.put("size", String.valueOf(mp3Info.getSize()));
			map.put("url", mp3Info.getUrl());
			mp3list.add(map);
		}
		mAdapter = new SimpleAdapter(this, mp3list, R.layout.all_music_list,
				new String[] { "title", "Artist", "duration" }, new int[] {
						R.id.name, R.id.artist });
		listView.setAdapter(mAdapter);
	}

}